﻿using AutoMapper;
using BaseData.CommonLib.Models;
using BaseData.DomainLib.AggregatesModel.MaterialAggregate;
using MediatR;
using Swimj.CommonLib.Base;

namespace BaseData.ApplicationLib.Commands
{
    public class UpdateMaterialCommand : MaterialEditRequestDto, IRequest<Result<MaterialInfoResponseDto>>
    {
        public int Id { get; set; }
    }

    public class UpdateMaterialCommandHandler : IRequestHandler<UpdateMaterialCommand, Result<MaterialInfoResponseDto>>
    {
        private readonly IMaterialRepository _materialRepository;
        private readonly IMapper _mapper;

        public UpdateMaterialCommandHandler(IMaterialRepository materialRepository,
            IMapper mapper)
        {
            _materialRepository = materialRepository;
            _mapper = mapper;
        }

        public async Task<Result<MaterialInfoResponseDto>> Handle(UpdateMaterialCommand request, CancellationToken cancellationToken)
        {
            var material = await _materialRepository.Get(request.Id);
            material?.Update(request.Code, request.Name, request.MaterialType,
                request.Specification, request.Unit, request.Sort, request.Description);

            await _materialRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);

            return await Result<MaterialInfoResponseDto>.SuccessAsync(_mapper.Map<MaterialInfoResponseDto>(material));
        }
    }
}